package top.hkyzf.study.leetcode.hash;

import org.junit.Test;

/**
 * @author 朱峰
 * @date 2022-1-24 10:36
 */
public class 字符串的排列_567 {
    public boolean checkInclusion(String s1, String s2) {
        int m = s1.length(), n = s2.length();
        if (m > n) {
            return false;
        }
        int[] cnt = new int[26];
        for (char c : s1.toCharArray()) {
            cnt[c - 'a']++;
        }
        int[] cur = new int[26];
        for (int i = 0; i < m; i++) {
            cur[s2.charAt(i) - 'a']++;
        }
        if (check(cnt, cur)) {
            return true;
        }
        for (int i = m; i < n; i++) {
            cur[s2.charAt(i) - 'a']++;
            cur[s2.charAt(i - m) - 'a']--;
            if (check(cnt, cur)) {
                return true;
            }
        }
        return false;
    }

    public boolean checkInclusion1(String s1, String s2) {
        int length1 = s1.length();
        int length2 = s2.length();
        if (length1 > length2) {
            return false;
        }
        int[] count = new int[26];
        int[] current = new int[26];
        for (int i = 0; i < length1; i++) {
            count[s1.charAt(i) - 'a']++;
            current[s2.charAt(i) - 'a']++;
        }
        if (check(count, current)) {
            return true;
        }
        for (int i = length1; i < length2; i++) {
            current[s2.charAt(i) - 'a']++;
            current[s2.charAt(i - length1) - 'a']--;
            if (check(count, current)) {
                return true;
            }
        }
        return false;
    }

    boolean check(int[] cnt1, int[] cnt2) {
        for (int i = 0; i < 26; i++) {
            if (cnt1[i] != cnt2[i]) return false;
        }
        return true;
    }

    @Test
    public void testCheckInclusion() {
        System.out.println(checkInclusion1("ab", "eidbaooo"));
    }
}
